package dj.action;

import java.util.ArrayList;
import java.util.List;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ModelDriven;

import dj.Constant;
import dj.action.base.BaseAction;
import dj.pageModel.Pmenu;
import dj.pageModel.Puser;
import dj.service.MenuService;

@Action("menuAction")
public class MenuAction extends BaseAction implements ModelDriven<Pmenu> {

	private Pmenu pmenu = new Pmenu();

	private MenuService menuService;

	public Pmenu getPmenu() {
		return pmenu;
	}

	public void setPmenu(Pmenu pmenu) {
		this.pmenu = pmenu;
	}

	public Pmenu getModel() {
		return pmenu;
	}

	public MenuService getMenuService() {
		return menuService;
	}

	@Autowired
	public void setMenuService(MenuService menuService) {
		this.menuService = menuService;
	}

	public void getTopMenu() {
		Puser puser = (Puser) ServletActionContext.getRequest().getSession().getAttribute(Constant.USER_SESSION);

		List<Pmenu> retMenus = new ArrayList<Pmenu>();
		List<Pmenu> menus = Constant.MENU_USER_KEY_MAP.get(puser.getId());

		if (null != menus && menus.size() > 0) {
			for (Pmenu m : menus) {
				if (null == m.getPid()) {
					retMenus.add(m);
				}
			}
		}

		super.writeToJson(retMenus);
	}

	public void getMenuByPid() {
		Puser puser = (Puser) ServletActionContext.getRequest().getSession().getAttribute(Constant.USER_SESSION);

		List<Pmenu> retMenus = new ArrayList<Pmenu>();
		List<Pmenu> menus = Constant.MENU_USER_KEY_MAP.get(puser.getId());

		if (null != menus && menus.size() > 0) {
			for (Pmenu m : menus) {
				if (pmenu.getPid().equals(m.getPid())) {
					retMenus.add(m);
					List<Pmenu> children = menuService.getMenuChildren(m, menus);
					if(children.size() > 0) {
						m.setState("closed");
						retMenus.addAll(children);
					}
				}
			}
		}

		super.writeToJson(retMenus);
	}
}
